<template>
  <div class="app-container" >
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="名称" prop="lastName">
          <el-input
            v-model="queryParams.lastName"
            placeholder="请输入名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="是否在世" prop="alive">
          <Dict v-model="queryParams.alive" code="alive" clearable/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button
          v-if="hasAuth(['genealogy:person:add']) && pageData.length === 0"
          type="success"
          icon="Plus"
          @click="handleOpenDialog()"
        >
          新增
        </el-button>
        <el-button
          v-if="hasAuth(['genealogy:person:delete'])"
          type="danger"
          icon="Delete"
          :disabled="removeIds.length === 0"
          @click="handleDelete()"
        >
          批量删除
        </el-button>
      </div>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="pageData"
        highlight-current-row
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column key="id" label="ID" prop="id" width="60" align="center" />
        <el-table-column
          key="familyId"
          label="所属家族"
          prop="familyName"
          min-width="120"
          align="center"
        />
        <el-table-column
          key="firstName"
          label="姓"
          prop="firstName"
          width="60"
          align="center"
        />
        <el-table-column
          key="lastName"
          label="名"
          prop="lastName"
          width="140"
          align="center"
        />
        <el-table-column
          key="nickname"
          label="昵称"
          prop="nickname"
          min-width="80"
          align="center"
        >
        </el-table-column>
        <el-table-column
          key="genation"
          label="字辈"
          prop="genation"
          min-width="80"
          align="center"
        >
          <template #default="scope">
            <DictLabel v-model="scope.row.genation" code="zibei" />
          </template>
        </el-table-column>
                <el-table-column
          label="性别"
          prop="gender"
          width="80"
          align="center"
        >
          <template #default="scope">
            <DictLabel v-model="scope.row.gender" code="gender" />
          </template>
        </el-table-column>
        <el-table-column
          label="是否在世"
          prop="alive"
          width="100"
          align="center"
        >
          <template #default="scope">
            <DictLabel v-model="scope.row.alive" code="alive" />
          </template>
        </el-table-column>
        <el-table-column
          key="photoUrl"
          label="头像照片123"
          prop="photoUrl"
          width="120"
          align="center"
        >
          <template #default="scope">
            <el-image 
              :src="scope.row.photoUrl" 
              style="width: 60px; height: 60px;" 
              :preview-src-list="[scope.row.photoUrl]"
              :initial-index="0"
              preview-teleported
              fit="cover"
              class="person-avatar"
              :preview-options="{
                zIndex: 3000,
                closeOnPressEscape: true,
                teleported: true
              }"
            >
            <template #error>
              <div class="image-slot">
                <img src="/public/TodayMen.png" style="width: 60px; height: 60px;" />
              </div>
            </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column
          key="birthDate"
          label="出生日期"
          prop="birthDate"
          min-width="120"
          align="center"
        />
        <el-table-column
          key="birthPlace"
          label="籍贯"
          prop="birthPlace"
          min-width="120"
          align="center"
        />
        <el-table-column
          key="parentId"
          label="父亲"
          prop="parentName"
          min-width="80"
          align="center"
        />

        <el-table-column fixed="right" label="操作" width="150" align="center">
          <template #default="scope">
            <el-dropdown trigger="click" @command="command => handleCommand(command, scope.row.id)">
              <el-button type="primary" size="small">
                操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item v-if="hasAuth(['genealogy:person:edit']) && (baseFlag === 1 || scope.row.familyId === userFamilyId)" command="edit">
                    <el-icon><Edit /></el-icon> 编辑
                  </el-dropdown-item>
                  <!-- <el-dropdown-item v-if="scope.row.parentId==null && hasAuth(['genealogy:person:edit']) && (baseFlag === 1 || scope.row.familyId === userFamilyId)" command="addParent">
                    <el-icon><Plus /></el-icon> 添加父辈
                  </el-dropdown-item>
                  <el-dropdown-item v-if="hasAuth(['genealogy:person:edit']) && (baseFlag === 1 || scope.row.familyId === userFamilyId)" command="addSpouse">
                    <el-icon><Plus /></el-icon> 添加配偶
                  </el-dropdown-item>
                  <el-dropdown-item v-if="hasAuth(['genealogy:person:edit']) && (baseFlag === 1 || scope.row.familyId === userFamilyId)" command="addChild">
                    <el-icon><Plus /></el-icon> 添加子辈
                  </el-dropdown-item> -->
                  <el-dropdown-item command="viewFamily">
                    <el-icon><View /></el-icon> 查看家谱
                  </el-dropdown-item>
                  <el-dropdown-item command="viewNineFamily">
                    <el-icon><View /></el-icon> 查看九族图
                  </el-dropdown-item>
                  <el-dropdown-item command="viewEighteenFamily">
                    <el-icon><View /></el-icon> 查看十八代
                  </el-dropdown-item>
                  <el-dropdown-item v-if="hasAuth(['genealogy:person:delete']) && (baseFlag === 1 || scope.row.familyId === userFamilyId)" command="delete" divided>
                    <el-icon><Delete /></el-icon> 删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery()"
      />
    </el-card>

    <!-- 家族信息表单弹窗 -->
    <el-drawer
      v-model="dialog.visible"
      :title="dialog.title"
      :size="drawerSize"
      @close="handleCloseDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="所属家族" prop="familyId">
              <el-select v-model="formData.familyId" placeholder="请选择" style="width: 100%">
                <el-option
                  v-for="item in familyOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓" prop="firstName">
              <el-input v-model="formData.firstName" placeholder="请输入姓" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="名" prop="lastName">
              <el-input v-model="formData.lastName" placeholder="请输入名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="formData.nickname" placeholder="请输入昵称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="字辈" prop="genation">
              <Dict v-model="formData.genation" code="zibei" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <Dict v-model="formData.gender" code="gender" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否在世" prop="alive">
              <el-popconfirm
                class="box-item"
                title="去世改成在世需要消耗在世点"
                placement="top-start"
              >
                <template #reference>
                  <Dict v-model="formData.alive" code="alive" @click="onSelect"/>
                </template>
              </el-popconfirm>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="头像照片" prop="photoUrl">
              <SingleImageUpload v-model="formData.photoUrl" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职业" prop="occupation">
              <el-input v-model="formData.occupation" placeholder="请输入职业" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="籍贯" prop="birthPlace">
              <el-input v-model="formData.birthPlace" placeholder="请输入籍贯" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="地址" prop="address">
              <el-input v-model="formData.address" placeholder="请输入地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经度" prop="longitude">
              <el-input v-model="formData.longitude" placeholder="请输入经度" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纬度" prop="latitude">
              <el-input v-model="formData.latitude" placeholder="请输入纬度" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生日期" prop="birthDate">
              <el-date-picker
                v-model="formData.birthDate"
                type="datetime"
                placeholder="请选择出生日期"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="死亡日期" prop="deathDate">
              <el-date-picker
                v-model="formData.deathDate"
                type="datetime"
                placeholder="请选择死亡日期"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="个人简介" prop="biography">
              <el-input
                type="textarea"
                rows="3"
                v-model="formData.biography"
                placeholder="请输入个人简介"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit(type)">确定</el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import PersonAPI from "@/api/genealogy/person.api";
import FamilyAPI from "@/api/genealogy/family.api";
import { DeviceEnum } from "@/enums/index.js";
import { useAppStore } from "@/store/index.js";
import { useRoute, useRouter } from "vue-router";
import { ArrowDown } from '@element-plus/icons-vue';
import { hasAuth } from "@/plugins/permission";
import { getDefaultAvatar } from "@/utils/avatar";
import { watch } from "vue";
import { useUserStore } from "@/store";
const { userFamilyId,baseFlag } = useUserStore().userInfo;

const appStore = useAppStore();
const router = useRouter();
defineOptions({
  name: "Person",
  inheritAttrs: false,
});
const drawerSize = computed(() => (appStore.device === DeviceEnum.DESKTOP ? "600px" : "90%"));
const queryFormRef = ref();
const dataFormRef = ref();
const loading = ref(false);
const removeIds = ref([]);
const total = ref(0);
const route = useRoute();
const familyId = route?.params?.familyId;
const familyOptions = ref();
const type = ref(0);
const queryParams = reactive({
  familyId: isNumber(familyId) ? familyId : null,
  lastName: "",
  alive: null,
  pageNum: 1,
  pageSize: 10,
});
//const picUrl = ref("https://s2.loli.net/2023/05/24/yNsxFC8rLHMZQcK.jpg");
// 家族信息表格数据
const pageData = ref([]);

// 弹窗
const dialog = reactive({
  title: "新增成员",
  visible: false,
  type: 0
});

// 初始行政区划表单数据
const initialFormData = ref({
  id: undefined,
  firstName: "",
  lastName: "",
  gender: 1,
  alive: 1,
  photoUrl: getDefaultAvatar({ gender: 1, birthDate: "" }),
});
// 家族信息表单数据
const formData = ref({ ...initialFormData.value });

// 家族信息表单校验规则
const rules = reactive({
  firstName: [{ required: true, message: "请输入姓", trigger: "blur" }],
  lastName: [{ required: true, message: "请输入名", trigger: "blur" }],
  gender: [{ required: true, message: "请输入性别", trigger: "blur" }],
  alive: [{ required: true, message: "请输入是否在世", trigger: "blur" }],
});

function isNumber(data) {
  return !isNaN(data) && !isNaN(parseFloat(data));
}

/** 查询家族信息 */
function handleQuery() {
  loading.value = true;
  PersonAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
      pageData.value.map(data1 => {
        if (Array.isArray(familyOptions.value)) {
          data1.familyName = familyOptions.value.filter(item => item.value === data1.familyId)[0]?.label;
        } else {
          data1.familyName = '';
        }
      });
    })
    .finally(() => {
      loading.value = false;
    });
}

function onSelect() {
  console.log(111);
}

/** 重置家族信息查询 */
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection) {
  removeIds.value = selection.map((item) => item.id);
}

/** 打开家族信息弹窗 弹出编辑信息 */
function handleOpenDialog(id) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改成员信息";
    PersonAPI.getFormData(id).then((data) => {
      Object.assign(formData.value, data);
    });
  } else {
    dialog.title = "新增成员信息";
  }
}

/** 打开人员信息弹窗 */
function handleOpenDialogTwo(type_param, personId) {
  if (4 === type_param) {
    // Redirect to familyShow page with personId as query parameter
    router.push({
      name: "FamilyShow",
      params: { personId: personId },
      query: { type: "all" },
    });
    return;
  } else if (5 === type_param) {
    // Redirect to familyShow page with personId as query parameter for 九族图
    router.push({
      name: "FamilyShow",
      params: { personId: personId },
      query: { type: "four" },
    });
    return;
  } else if (6 === type_param) {
    // Redirect to familyShow page with personId as query parameter for 十八代
    router.push({
      name: "FamilyShow",
      params: { personId: personId },
      query: { type: "nine" },
    });
    return;
  }

  dialog.visible = true;
  PersonAPI.getFormData(personId).then((data) => {
    formData.value.familyId = data.familyId;

    type.value = type_param;
    if (1 === type_param) {
      dialog.title = "新增父辈成员信息";
      formData.value.personId = personId;
      formData.value.type = type_param;
    } else if (2 === type_param) {
      dialog.title = "新增配偶成员信息";
      formData.value.flag = 1;
      formData.value.type = type_param;
      formData.value.personId = personId;
    } else if (3 === type_param) {
      dialog.title = "新增子辈成员信息";
      formData.value.type = type_param;
      formData.value.personId = personId;
    }
  });
}

/** 提交家族信息表单 */
function handleSubmit(type) {
  if (type === 0) {
    dataFormRef.value.validate((valid) => {
      if (valid) {
        loading.value = true;
        const id = formData.value.id;
        if (id) {
          PersonAPI.update(id, formData.value)
            .then(() => {
              ElMessage.success("修改成功");
              handleCloseDialog();
              handleResetQuery();
            })
            .finally(() => (loading.value = false));
        } else {
          PersonAPI.create(formData.value)
            .then(() => {
              ElMessage.success("新增成功");
              handleCloseDialog();
              handleResetQuery();
            })
            .finally(() => (loading.value = false));
        }
      }
    });
  } else {
    // formData.value.personId = formData.value.id;
    PersonAPI.createByType(formData.value)
      .then(() => {
        ElMessage.success("新增成功");
        handleCloseDialog();
        handleResetQuery();
      })
      .finally(() => (loading.value = false));
  }
}

/** 关闭家族信息弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id = undefined;
}

/** 删除家族信息 */
function handleDelete(id) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      PersonAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

/** 处理操作下拉菜单命令 */
function handleCommand(command, personId) {
  switch (command) {
    case "edit":
      handleOpenDialog(personId);
      break;
    case "addParent":
      handleOpenDialogTwo(1, personId);
      break;
    case "addSpouse":
      handleOpenDialogTwo(2, personId);
      break;
    case "addChild":
      handleOpenDialogTwo(3, personId);
      break;
    case "viewFamily":
      handleOpenDialogTwo(4, personId);
      break;
    case "viewNineFamily":
      handleOpenDialogTwo(5, personId);
      break;
    case "viewEighteenFamily":
      handleOpenDialogTwo(6, personId);
      break;
    case "delete":
      handleDelete(personId);
      break;
  }
}

// 判断当前头像是否为默认头像
function isDefaultAvatar(photoUrl, gender, birthDate) {
  return photoUrl === getDefaultAvatar({ gender, birthDate });
}

// 监听性别和出生日期变化，自动更新默认头像
watch(
  () => [formData.value.gender, formData.value.birthDate],
  ([newGender, newBirthDate], [oldGender, oldBirthDate]) => {
    // 只有当头像是默认头像时才自动更新
    if (isDefaultAvatar(formData.value.photoUrl, oldGender, oldBirthDate)) {
      formData.value.photoUrl = getDefaultAvatar({
        gender: newGender,
        birthDate: newBirthDate,
      });
    }
  }
);

onBeforeMount(() => {
  FamilyAPI.getOptions().then((data) => {
    familyOptions.value = data;
  });
});
onMounted(() => {
  handleQuery();
  console.info("familyId =" + familyId);
});
</script>

<style scoped>
.person-avatar {
  cursor: pointer;
  border-radius: 4px;
  transition: transform 0.2s;
}
.person-avatar:hover {
  transform: scale(1.05);
}
</style>
